<template>
  <ul class="tree-ul">
    <li class="tree-li">
      <span
        v-if="data.children && data.children.length"
        :class="['tree-expand', data.expand ? 'up' : 'right']"
        @click="handleExpand"
      />
      <g-checkbox v-if="showCheckbox" :value="data.checked" @change="handleCheck" />
      <span class="tree-title">{{ data.title }}</span>
      <template v-if="data.expand">
        <tree-node v-for="(item, index) in data.children" :key="index" :data="item" :show-checkbox="showCheckbox" />
      </template>
    </li>
  </ul>
</template>

<script>
import { findComponentUpward } from '@/utils/assist'
export default {
  name: 'TreeNode',
  props: {
    data: {
      type: Object,
      default: () => {},
    },
    showCheckbox: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tree: findComponentUpward(this, 'tree'),
    }
  },
  watch: {
    'data.children': {
      handler(data) {
        if (data) {
          let checkedAll = !data.some(item => !item.checked)
          this.$set(this.data, 'checked', checkedAll)
        }
      },
      deep: true,
    },
  },
  methods: {
    handleExpand() {
      this.$set(this.data, 'expand', !this.data.expand) // 试图更新
      if (this.tree) {
        // 递归组件 有可能父级可能还是自己，$parent无法判断
        this.tree.emitEvent('on-toggle-expand', this.data)
      }
    },
    handleCheck(checked) {
      this.updateTreeDown(this.data, checked)
      if (this.tree) {
        this.tree.emitEvent('on-check-change', this.data)
      }
    },
    updateTreeDown(data, checked) {
      this.$set(data, 'checked', checked)
      if (data.children && data.children.length) {
        data.children.forEach(item => {
          this.updateTreeDown(item, checked)
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.tree-ul,
.tree-li {
  list-style: none;
  padding-left: 16px;
  line-height: 30px;
}
.tree-expand {
  cursor: pointer;
  display: inline-flex;
  &.up,
  &.right {
    width: 0px;
    height: 0px;
    font-size: 0px;
    line-height: 0px;
  }
  &.up {
    border-right: 8px solid transparent;
    border-left: 8px solid transparent;
    border-bottom: 10px solid #777;
  }
  &.right {
    border-bottom: 8px solid transparent;
    border-top: 8px solid transparent;
    border-left: 10px solid #ccc;
  }
}
.tree-title {
  // margin-left: 8px;
  font-size: 16px;
  color: #333;
}
</style>
